package com.xiaobaibai.security.master_token.filter;

import com.xiaobaibai.myExcetion.SecurityMyException;
import com.xiaobaibai.security.master_token.token.JwtAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.PostConstruct;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class No2JwtAuthenticationFilter extends OncePerRequestFilter {

    private AuthenticationManager authenticationManager;
    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    private AuthenticationFailureHandler failureHandler;

    private List<String> readyURI;

    private String excludeUri;

    public No2JwtAuthenticationFilter(String excludeUri) {
        this.excludeUri=excludeUri;
    }

    protected String getJwtToken(HttpServletRequest request) {
        String headerToken=request.getHeader("Authorization");
        //开始基于JWT的验证

        if(StringUtils.isBlank(headerToken)){
            //返回请携带令牌
            throw new SecurityMyException("请携带令牌");
        }

        return headerToken;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        boolean matches = this.matches(request);
        if(matches)//读取排除的url(无需权限的)
            filterChain.doFilter(request, response);
        else {
            Authentication authResult = null;
            AuthenticationException failed = null;

            try {
                String token = getJwtToken(request);
                JwtAuthenticationToken authToken = new JwtAuthenticationToken(token);
                authResult = this.getAuthenticationManager().authenticate(authToken);

            } catch (Exception e) {
                //这里异常了,那么authResult就会为空,那么就会走到下面的失败处理器
//                e.printStackTrace();
                //创建属于security的错误异常
                failed = new InsufficientAuthenticationException(e.getMessage(),e);
//                throw failed;
//                throw new SecurityMyException("非法令牌");
            }

            /**
             * 手动加入上下文,简书大佬如此写到,小白可以去参考BasicAuthenticationFilter
             */

            if (authResult != null) {
                successfulAuthentication(request, response, filterChain, authResult);
            } else {
                unsuccessfulAuthentication(request, response, failed);
                return;
            }

            filterChain.doFilter(request, response);
        }
    }

    @PostConstruct
    private void readyURI(){
        readyURI=new ArrayList<>();
        String matchURI=excludeUri;
        log.info("从yml中取出来的uri:"+excludeUri);
        String[] split = StringUtils.split(matchURI,",");
        for (int i = 0; i < split.length; i++) {
            split[i]="/mall-admin"+split[i];
        }
        readyURI.addAll(Arrays.asList(split));
    }

    private boolean matches(HttpServletRequest request){
        String thisURI=request.getRequestURI();
        for (String s : this.readyURI) {
            if(antPathMatcher.match(s,thisURI))
                return true;
        }
        return false;
    }

    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        SecurityContextHolder.clearContext();
        failureHandler.onAuthenticationFailure(request, response, failed);
    }

    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException{
        SecurityContextHolder.getContext().setAuthentication(authResult);
        successHandler.onAuthenticationSuccess(request, response, authResult);
    }

    protected AuthenticationManager getAuthenticationManager() {
        return authenticationManager;
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    public void setAuthenticationSuccessHandler(
            AuthenticationSuccessHandler successHandler) {
        Assert.notNull(successHandler, "successHandler cannot be null");
        this.successHandler = successHandler;
    }

    public void setAuthenticationFailureHandler(
            AuthenticationFailureHandler failureHandler) {
        Assert.notNull(failureHandler, "failureHandler cannot be null");
        this.failureHandler = failureHandler;
    }

    public void setFailureHandler(AuthenticationFailureHandler failureHandler) {
        this.failureHandler = failureHandler;
    }
}
